import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DialogService } from 'ng-devui';
import { OperableTreeComponent, TreeNode } from 'ng-devui/tree';
// import { userInfo } from 'os';
import { BroadcastService } from 'src/app/services/broadcast.service';
import { CommonDataService } from 'src/app/services/common-data.service';
import { MateDataService } from 'src/app/services/mate_data.service';
import { SessionService } from 'src/app/services/session.service';
import { AddUserComponent } from '../add-user/add-user.component';
import { LoginComponent } from '../login/login.component';

@Component({
    selector: 'app-files-tree',
    templateUrl: './files-tree.component.html',
    styleUrls: ['./files-tree.component.scss']
})
export class FilesTreeComponent implements OnInit {

    @ViewChild('operableTree', { static: false }) operableTree: OperableTreeComponent;
    userInfo: any;
    msgs: Array<Object> = [];
    data1 = [];
    successDel: any;
    constructor(
        private mateDataSrv: MateDataService,
        private commonDataSrv: CommonDataService,
        private broadcastSrv: BroadcastService,
        private dialogService: DialogService,
        private sessionSvc: SessionService,
        private router: Router
    ) {
        this.broadcastSrv.on('refreshTree').subscribe(res => {
            const newFileNode = res.newFileNode;
            const { label, orgId, objId } = newFileNode;
            const parentNode = this.operableTree.nodes.find(e => e.data.originItem.userId === res.userId);
            if (!parentNode || !parentNode.data.hasLoading) return
            this.operableTree.treeFactory.startLoading(parentNode.id);
            this.operableTree.treeFactory.mapTreeItems({ treeItems: [{ title: label, orgId, objId }], parentId: parentNode.id });
            this.operableTree.treeFactory.endLoading(parentNode.id);
        })
    }

    ngOnInit() {
        this.getUserInfoList();
    }

    async getUserInfoList() {
        //请求用户列表
        this.userInfo = this.sessionSvc.getSessionValue('user');
        let param;
        if (this.userInfo.roleName.toUpperCase() === 'NORMAL') {
            param = {
                userId: this.userInfo.userId
            };
        }
        const { status, result } = await this.mateDataSrv.getUserList(param) as any;
        if (status.toUpperCase() === 'SUCCESS') {
            this.data1 = result.map(e => {
                return {
                    title: e.userName,
                    userId: e.userId,
                    userName: e.userName,
                    disabled: false,
                    open: false,
                    isParent: true
                }
            })
        } else if (status.toUpperCase() === 'TOKEN_FAILURE') {
            this.msgs = [
                { severity: 'error', summary: '错误', content: '登录信息失效！请重新登录！' },
            ];
            this.router.navigate(['login'])
        }
    }

    onNodeSelected(treeNode: TreeNode) {
        console.log('treeNode', treeNode)
        if (treeNode.data.isParent) {
            this.router.navigate(['mainpage/userInfo'], { queryParams: { userId: treeNode.data.originItem.userId } })
        } else {
            this.router.navigate(['mainpage/excelTable'], { queryParams: { objId: treeNode.data.originItem.objId } });
        }

    }

    onNodeToggled(treeNode: TreeNode) {
        if (!treeNode.data.isOpen || treeNode.data.hasLoading) return
        this.loadChildren(treeNode);
        treeNode.data.hasLoading = true;
    }

    loadChildren(treeNode: TreeNode) {
        if (treeNode.data.isParent) {
            if (!this.operableTree.treeFactory.nodes[treeNode.id].data.loading) {
                this.operableTree.treeFactory.startLoading(treeNode.id);
                this.mateDataSrv.getFileData(treeNode.data.originItem.userId).subscribe((res: any) => {
                    if (res.status.toUpperCase() === 'SUCCESS') {
                        const items = res.result.map((e: any) => {
                            return {
                                title: e.label,
                                orgId: e.orgId,
                                objId: e.objId
                            }
                        })
                        this.operableTree.treeFactory.endLoading(treeNode.id);
                        this.operableTree.treeFactory.mapTreeItems({ treeItems: items, parentId: treeNode.id });
                    } else if (status.toUpperCase() === 'TOKEN_FAILURE') {
                        this.msgs = [
                            { severity: 'error', summary: '错误', content: '登录信息失效！请重新登录！' },
                        ];
                        this.router.navigate(['login'])
                    }
                });
            }
        }
    }

    onOperableNodeEdited(treeNode: TreeNode) {
        const params = {
            objId: treeNode.data.originItem.objId,
            label: treeNode.data.title,
            name: treeNode.data.title,
            lastModifiedBy: this.sessionSvc.getSessionValue('user').userName
        }
        this.mateDataSrv.modifyFileName(params).subscribe((res: any) => {
            if (res.status.toUpperCase() === 'SUCCESS') {
                treeNode.data.originItem.label = treeNode.data.title;
                treeNode.data.originItem.name = treeNode.data.title;
            } else {
                treeNode.data.title = treeNode.data.originItem.label;
            }
        })
    }

    editValueChange(event) {
        // 标记态校验节点，可通过传入errTips控制报错信息，errTipsPosition控制报错信息的弹出位置
        if (event.value === '') {
            event.callback({
                errTips: 'The node name cannot be null!',
                errTipsPosition: 'right'
            });
        } else {
            // 校验通过后调用callback,取消报错显示
            event.callback();
        }
    }

    beforeDeleteNode = (node) => {
        return new Promise(async (resolve, reject) => {
            if (!node.data.isParent) {
                const parentNode = this.operableTree.treeFactory.getNodeById(node.parentId);
                const modifiedBy = parentNode.originItem.userName;
                const file = node.data.originItem;
                const status: any = await this.openDeleteDialog(file, modifiedBy);
                if (status === 'SUCCESS') {
                    resolve(node)
                } else if (status.toUpperCase() === 'TOKEN_FAILURE') {
                    this.msgs = [
                        { severity: 'error', summary: '错误', content: '登录信息失效！请重新登录！' },
                    ];
                    this.router.navigate(['login']);
                }
            } else {
                if (this.userInfo.roleName.toUpperCase() === "NORMAL") {
                    this.msgs = [
                        { severity: 'info', summary: '提示', content: '你没有权限删除用户！' },
                    ];
                    return;
                } else {
                    let deleteUserInfo = {
                        userId: node.data.originItem.userId
                    }
                    console.log('delete node', node)
                    this.mateDataSrv.deleteUser(deleteUserInfo).subscribe((res: any) => {
                        const { status, result } = res;
                        if (status.toUpperCase() === 'SUCCESS') {
                            this.msgs = [
                                { severity: 'success', summary: '成功', content: '删除用户成功！' },
                            ];
                        }else if (status.toUpperCase() === 'TOKEN_FAILURE') {
                            this.msgs = [
                                { severity: 'error', summary: '错误', content: '登录信息失效！请重新登录！' },
                            ];
                            this.router.navigate(['login']);
                        }
                    })

                }
            }
        })
    }

    beforeEditNode = (node) => {
        return new Promise((resolve, reject) => {
            if (!node.data.isParent) {
                resolve(node);
            }
        });
    }

    onNodeDeleted(evt) {
        // this.broadcastSrv.broadcast('refreshTableData_left');
        this.router.navigate(['mainpage/excelTable'])
    }

    async openDeleteDialog(file, modifiedBy) {
        return new Promise((resolve, reject) => {
            const results = this.dialogService.open({
                id: 'dialog-service',
                width: '400px',
                maxHeight: '600px',
                title: '',
                html: true,
                content: '确认删除文件？',
                backdropCloseable: true,
                dialogtype: 'warning',
                buttons: [
                    {
                        cssClass: 'primary',
                        text: '确定',
                        handler: ($event: Event) => {
                            const status = this.deleteFile(file, modifiedBy);
                            resolve(status);
                            results.modalInstance.hide();
                        },
                    },
                    {
                        id: 'btn-cancel',
                        cssClass: 'common',
                        text: '取消',
                        handler: ($event: Event) => {
                            resolve('cancel');
                            results.modalInstance.hide();
                        },
                    },
                ],
            });
        })

    }

    async deleteFile(file, modifiedBy) {
        const res = await this.mateDataSrv.deleteFile(file.objId, modifiedBy).toPromise() as any;
        return res.status;
    }


    async openAddUserDialog() {
        if (this.userInfo.roleName.toUpperCase() === "NORMAL") {
            this.msgs = [
                { severity: 'info', summary: '提示', content: '你没有权限添加新用户！' },
            ]
            return;
        }
        console.log('openAddUserDialog')
        const results = this.dialogService.open({
            id: 'dialog-service',
            width: '600px',
            maxHeight: '600px',
            title: '添加新用户',
            content: AddUserComponent,
            backdropCloseable: true,
            dialogtype: 'standard',
            onClose: () => {
                console.log('on dialog closed');
            },
            buttons: [
                {
                    cssClass: 'primary',
                    text: '确定',
                    handler: ($event: Event) => {
                        //   console.log('tag created');
                        const { userInfo } = results.modalContentInstance;
                        this.addNewUser(userInfo);
                        results.modalInstance.hide();
                    },
                },
                {
                    id: 'btn-cancel',
                    cssClass: 'common',
                    text: '取消',
                    handler: ($event: Event) => {
                        results.modalInstance.hide();
                    },
                },
            ],
            // data: {
            //     branch:branch,
            // },
        });
        console.log('results.modalInstance', results.modalInstance)
    }

    async addNewUser(newUserinfo) {
        newUserinfo = { ...newUserinfo, createBy: this.userInfo.userName, lastModifiedBy: this.userInfo.userName };
        console.log('newUserinfo', newUserinfo);
        this.mateDataSrv.addNewUser(newUserinfo).subscribe((res: any) => {
            const { status, result } = res;
            if (status.toUpperCase() === 'SUCCESS') {
                this.msgs = [
                    { severity: 'success', summary: '成功', content: '添加新用户成功！' },
                ];
                this.getUserInfoList();
            }
        })
    }
}
